<?php 
class XaclComponent extends Object {


    var $components = array('Session');
    var $Tuser;
    var $controller;
    var $action_id;
    var $xaclData=array();


    //在Controller::beforeFilter()之前被调用
    function initialize($controller) {
        $this->controller = $controller;

        $this->Tuser = ClassRegistry::init('Tuser');
        $faction = $controller->name."::".$controller->action;
        if (method_exists($controller, $controller->action)) {
            $Taction = ClassRegistry::init('Taction');
            $Taction->action_collect($faction);
            $this->action_id = $Taction->getActionIdByName($faction);
        }

        if ($faction != 'Tuser::out' && $faction != 'Tuser::login' && $faction != 'Tuser::reest') {
            //print $faction;
            if (FALSE == $this->check_login()) {
                //$controller->flash("需要登录!", '/Tuser/login');
                $ref = isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : "/tuser/index";
                $this->redirectSomewhere('/tuser/login/'.base64_encode($ref),'请登录');

                return;
                //exit;
            }else{
                $this->xaclData = $this->getXaclData();
                $xaclData = $this->xaclData ;
                if(!in_array($this->action_id,$xaclData['ACL']))
                {
                    $this->redirectSomewhere('/tuser/reest/');
                    return;
                }
                $this->load_menu($controller);
            }
        }
    }
    //在Controller::beforeFilter()之后被调用
    function startup(&$controller) {
    }
    /**
     * 通过 controller跳转
     * @param string $value 地址
     * @param string $txt	flash提示信息
     */
    function redirectSomewhere($value,$txt = NULL) {
        // 使用控制器的方法
   
        if(NULL !=trim($txt))
        {
           $this->Session->write('refmsg',$txt);        	
                         
        } 
        echo '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title></title></head><body><script language="javascript">window.location="'.$value.'";</script></body></html>';
        exit;
    }

    /**
     * 登录检测
     * @return bool
     */
    function check_login() {
        if (FALSE == $this->Session->read('is_login')) {
            return FALSE;
        }
        return TRUE;
    }
    /**
      * 保存登录信息并跳转
      *
      * @param string $user 用户名
      * @param string $url	跳转地址
      * @return bool
      */
    function write_login($user = NULL,$url =NULL) {
        $url = empty($url) ? '/tuser/index' : $url;
        if (NULL == $user) {
            return FALSE;
        }
        $user_info = $this->Tuser->findByUserName($user);
        $this->Session->write("_user", $user_info);
        $this->Session->write("is_login", TRUE);
        $this->redirectSomewhere($url,"登录成功!");
    }

    /**
     * 得到当前用户信息
     * @return	Array
     */
    function currentUser() {
        if (FALSE == $this->Session->read('is_login')) {
            //$this->Session->write("ref", $where);
            return FALSE;
        } else {
            return $this->Session->read("_user");
        }

    }

    /**
     *登出
     * @return
     */
    function logout() {
        $ref = "/tuser/login";
        $this->Session->destroy();
        $this->redirectSomewhere($ref,"登出成功!");
    }
    /**
     * 载入菜单
     *
     * @param object $controller
     */
    function load_menu(&$controller) {

        $data = $this->Session->read('_MenuTree');
        if(NULL == $data)
        {
            $Tmenu = ClassRegistry::init('Tmenu');
            $data = '[';

            $treeData = $Tmenu->getSubMenu('0');
            // print_r($treeData);exit;
            $data.=join(",",$this->mktreeDta($treeData));
            $data .= ']';
            $this->Session->write('_MenuTree',$data);
        }
        $controller->set('menu_data', $data);
    }
    /**
     * 整理树菜单
     * @param Array $data
     * @return Array
     */
    function mktreeDta($data)
    {
        $tmpArr =Array();
        $xaclData = $this->xaclData ;

        foreach ($data as $val)
        {
            if(!empty($val['f_name']) && in_array($val['id'],$xaclData['MENU']))
            {
                $tmpArr[]="['".trim($val['f_name'])."', '".trim($val['f_url'])."']";
                if (count($val['sub']) > 0)
                {
                    $tmpArr[] ="[".join(',',$this->mktreeDta($val['sub']))."]";
                }


            }
        }
        return $tmpArr;
    }
    /**
     * 载入用户菜单、权限信息
     *
     * @return Array
     */
    function getXaclData()
    {

        $result = $this->Session->read('_Xacl');
        if(NULL==$result)
        {
            $result =array
            (
            "ACL"=>array(),
            "MENU"=>array()
            );
            $user_info = $this->currentUser();
            if(false == $user_info)
            {
                return $result;
            }
            $uid = $user_info['Tuser']['id'];

            $Tusergrouprelation = ClassRegistry::init('Tusergrouprelation');
            $Tmenugrouprelation = ClassRegistry::init('Tmenugrouprelation');
            $Tactiongrouprelation = ClassRegistry::init('Tactiongrouprelation');

            $usergroups =$Tusergrouprelation->getUserGroups($uid);
            if(empty($usergroups))
            {
                return $result;
            }
            $conditions = "f_gid in('".join("','",$usergroups)."') ";
            $rs1 = $Tmenugrouprelation->findAll($conditions);
            $rs2 = $Tactiongrouprelation->findAll($conditions);

            if(0<count($rs1))
            {
                foreach ($rs1 as $v1) {
                    if(!in_array($v1['Tmenugrouprelation']['f_mid'],$result['MENU']))
                    {
                        $result['MENU'][] = $v1['Tmenugrouprelation']['f_mid'];
                    }
                }
            }

            if(0<count($rs2))
            {
                foreach ($rs2 as $v2) {
                    if(!in_array($v2['Tactiongrouprelation']['f_aid'],$result['ACL']))
                    {
                        $result['ACL'][] = $v2['Tactiongrouprelation']['f_aid'];
                    }
                }
            }
            $this->Session->write('_Xacl',$result);
            unset($Tusergrouprelation);
            unset($Tmenugrouprelation);
            unset($Tactiongrouprelation);
        }
        return $result;
    }
}
?>
